package rexsee.device;

import java.io.File;
import java.io.FileOutputStream;

import rexsee.core.browser.Browser;
import rexsee.core.browser.clazz.JavascriptInterface;
import rexsee.core.browser.clazz.RootViewInterface;
import rexsee.core.utilities.Utilities;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

public class RexseeScreen implements JavascriptInterface {

	public static final String INTERFACE_NAME = "Screen";
	@Override
	public String getInterfaceName() {
		return mBrowser.application.resources.prefix + INTERFACE_NAME;
	}
	@Override
	public JavascriptInterface getInheritInterface(Browser childBrowser) {
		return this;
	}
	@Override
	public JavascriptInterface getNewInterface(Browser childBrowser) {
		return null;
	}

	public static final String SCREEN_ORIENTATION_PORTRAIT = "portrait";
	public static final String SCREEN_ORIENTATION_LANDSCAPE = "landscape";
	public static final String SCREEN_ORIENTATION_AUTO = "auto";

	public String screenOrientation = SCREEN_ORIENTATION_AUTO;
	public boolean fullScreen = false;
	public boolean screenAlwaysOn = false;

	private final Browser mBrowser;
	private final Context mContext;
	private final RootViewInterface mLayout;

	public RexseeScreen(RootViewInterface rootView) {
		mLayout = rootView;
		mBrowser = rootView.getBrowser();
		mContext = mBrowser.getContext();
		if (!mBrowser.application.resources.screenOrientation.equalsIgnoreCase("none")) {
			setScreenOrientation(mBrowser.application.resources.screenOrientation);
		}
	}
	public static boolean printView(Browser browser, String path, View view, boolean png, int quality) {
		Bitmap.CompressFormat format = (png) ? Bitmap.CompressFormat.PNG : Bitmap.CompressFormat.JPEG;
		File file = Utilities.prepareWriteFile(path);
		if (file == null) {
			browser.exception("printView", "Invalid path.");
			return false;
		}
		view.setDrawingCacheEnabled(true);
		view.destroyDrawingCache();
		Bitmap bitmap = view.getDrawingCache();
		if (bitmap == null) {
			browser.exception("printView", "Print layout error.");
			return false;
		}
		try {
			FileOutputStream fileOutput = new FileOutputStream(file);
			boolean rtn = bitmap.compress(format, quality, fileOutput);
			fileOutput.flush();
			fileOutput.close();
			bitmap.recycle();
			bitmap = null;
			return rtn;
		} catch (Exception e) {
			browser.exception("printView", e);
			return false;
		}
	}

	//JavaScript Interface
	public void setScreenOrientation(String orientation) {
		if (orientation.equalsIgnoreCase(SCREEN_ORIENTATION_PORTRAIT)) {
			screenOrientation = SCREEN_ORIENTATION_PORTRAIT;
			((Activity) mContext).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		} else if (orientation.equalsIgnoreCase(SCREEN_ORIENTATION_LANDSCAPE)) {
			screenOrientation = SCREEN_ORIENTATION_LANDSCAPE;
			((Activity) mContext).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		} else {
			screenOrientation = SCREEN_ORIENTATION_AUTO;
			((Activity) mContext).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
		}
	}
	public void toggleScreenOrientation() {
		if (screenOrientation.equals(SCREEN_ORIENTATION_PORTRAIT)) {
			setScreenOrientation(SCREEN_ORIENTATION_LANDSCAPE);
		} else if (screenOrientation.equals(SCREEN_ORIENTATION_LANDSCAPE)) {
			setScreenOrientation(SCREEN_ORIENTATION_PORTRAIT);
		}
	}
	public String getScreenOrientation() {
		return screenOrientation;
	}
	public String getCurrentScreenOrientation() {
		DisplayMetrics displayMetrics = new DisplayMetrics();
		((Activity) mContext).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
		return (displayMetrics.widthPixels > displayMetrics.heightPixels) ? SCREEN_ORIENTATION_LANDSCAPE : SCREEN_ORIENTATION_PORTRAIT;
	}

	public void setFullScreen(final boolean isFullScreen) {
		fullScreen = isFullScreen;
		((Activity) mContext).runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (isFullScreen) {
					((Activity) mContext).getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
				} else {
					((Activity) mContext).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
				}
			}
		});
	}
	public boolean isFullScreen() {
		return fullScreen;
	}
	public int getScreenWidth() {
		return mBrowser.application.screenWidth;
	}
	public int getScreenHeight() {
		return mBrowser.application.screenHeight;
	}
	public float getScreenDensityScale() {
		return mBrowser.application.screenDensity;
	}
	public int getNoticeBarHeight() {
		return (fullScreen) ? 0 : mLayout.getRect().top;
	}

	public void setScreenAlwaysOn(final boolean isAlwaysOn) {
		screenAlwaysOn = isAlwaysOn;
		((Activity) mContext).runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (isAlwaysOn) {
					((Activity) mContext).getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
				} else {
					((Activity) mContext).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
				}
			}
		});
	}
	public boolean isScreenAlwaysOn() {
		return screenAlwaysOn;
	}

	public boolean printLayout(String path, boolean isPng, int jpegQuality) {
		return printView(mBrowser, path, mLayout.getView(), isPng, jpegQuality);
	}
	public boolean printBrowser(String path, boolean isPng, int jpegQuality) {
		return printView(mBrowser, path, mBrowser, isPng, jpegQuality);
	}

	public void enableAutomaticBrightness(boolean enable) {
		try {
			ContentResolver resolver = mContext.getContentResolver();
			Settings.System.putInt(resolver, "screen_brightness_mode", (enable) ? 1 : 0);
		} catch (Exception e) {
			mBrowser.exception(getInterfaceName(), e);
		}
	}
	public boolean isAutomaticBrightnessEnabled() {
		try {
			ContentResolver resolver = mContext.getContentResolver();
			return Settings.System.getInt(resolver, "screen_brightness_mode") == 1;
		} catch (Exception e) {
			mBrowser.exception(getInterfaceName(), e);
			return false;
		}
	}
	public int getScreenBrightness() {
		try {
			ContentResolver resolver = mContext.getContentResolver();
			return Settings.System.getInt(resolver, Settings.System.SCREEN_BRIGHTNESS);
		} catch (Exception e) {
			mBrowser.exception(getInterfaceName(), e);
			return -1;
		}
	}
	public void setScreenBrightness(final int brightness, final boolean save) {
		try {
			((Activity) mContext).runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Window window = ((Activity) mContext).getWindow();
					WindowManager.LayoutParams lp = window.getAttributes();
					lp.screenBrightness = Float.valueOf(brightness) * (1f / 255f);
					window.setAttributes(lp);
				}
			});
			if (save) {
				ContentResolver resolver = mContext.getContentResolver();
				Uri uri = Settings.System.getUriFor("screen_brightness");
				Settings.System.putInt(resolver, "screen_brightness", brightness);
				resolver.notifyChange(uri, null);
			}
		} catch (Exception e) {
			mBrowser.exception(getInterfaceName(), e);
		}
	}

}
